package com.yingside.collection;

import java.util.ArrayList;

public class StudentManager {
    ArrayList<Student> stuList;

    public StudentManager() {
        this.stuList = new ArrayList<>();
    }

    public void show(){
        System.out.println("编号\t姓名\t电话");
        for (int i = 0; i < stuList.size(); i++) {
            Student s = stuList.get(i);
            System.out.println(s.getId() + "\t"
                + s.getName() + "\t"
                + s.getTel());
        }
    }

    public void addStudent(Student stu){
        if(stu == null || stu.getId() < 0){
            throw new RuntimeException("参数不能为null或者id不能小于0");
        }
        int index = this.findById(stu.getId());
        if(index == -1){
            this.stuList.add(stu);
        }
        else{
            throw new RuntimeException("学生id已经存在，不能保存一样的id");
        }
    }

    /**
     * 查找学生id在集合中是否存在
     * @param id 学生id
     * @return 如果存在返回集合下标，如果不存在返回-1
     */
    public int findById(int id){
        int index = -1;
        for (int i = 0; i < stuList.size(); i++) {
            if(stuList.get(i).getId() == id){
                index = i;
                break;
            }
        }
        return index;
    }

    /**
     * 根据学生id查找学生对象
     * @param id 学生id
     * @return 查找成功返回学生对象，查找失败直接抛出异常
     */
    public Student findStudent(int id){
        Student s = null;
        if(id < 0){
            throw new RuntimeException("学生id不能小于0");
        }

        int index = this.findById(id);

        if(index == -1){
            throw new RuntimeException("不存在这样的学生id，查询错误");
        }
        else{
            s = this.stuList.get(index);
        }
        return s;
    }

    public static void main(String[] args) {
        StudentManager studentManager = new StudentManager();
        Student s1 = new Student(1,"宁宁1","1242354361");
        Student s2 = new Student(2,"宁宁2","1242354362");
        Student s3 = new Student(3,"宁宁3","1242354363");

        studentManager.addStudent(s1);
        studentManager.addStudent(s2);
        studentManager.addStudent(s3);


        studentManager.show();

//        Student s4 = new Student(3,"宁宁3","1242354363");
//        studentManager.addStudent(s4);

        Student student = studentManager.findStudent(-1);
        System.out.println("student = " + student);
    }
}
